# -*- coding:utf-8 -*-
# Created by Jin(jinzhencheng@outlook.com) at 2018/8/1 15:16

from random import choice

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

from bd_spider.config import GenerationConfig


class BrowserFactory(object):

    def __init__(self, proxy=None, user_agent=None, cookies = None):
        self.__proxy = proxy
        self.__user_agent = user_agent if user_agent else choice(GenerationConfig.USER_AGENTS)
        self.__cookies = cookies
        self.browser = None

    def __init_phantom(self):
        """
        Initializes a new instance of PhantomJS
        :return: fake browser
        """
        dcap = dict(DesiredCapabilities.PHANTOMJS)
        dcap["phantomjs.page.settings.userAgent"] = self.__user_agent
        dcap["phantomjs.page.settings.loadImages"] = False
        service_args = [
            '--proxy-type=http',
            '--load-images=no',
            '--disk-cache=yes',
            '--ignore-ssl-errors=true'
        ]
        if self.__proxy:
            service_args.append('--proxy=%s' % self.__proxy)
        self.browser = webdriver.PhantomJS(desired_capabilities=dcap, service_args=service_args)
        if self.__cookies:
            self.browser.add_cookie(self.__cookies)

    def create(self):
        self.__init_phantom()
        return self.browser

    def quit(self, browser):
        if browser:
            browser.quit()